layui.define(['form'], function (exports) {
    "use strict";

    var TreeSelect = function () {
            this.v = '0.1';
        }, _MOD = 'treeSelect',
        _this = this,
        form = layui.form,
        $ = layui.jquery,
        BODY = 'body',
        TIPS = '未选择数据';

    /**
     * 渲染组件
     */
    TreeSelect.prototype.render = function (options) {
        var opts = options,
            // DOM选择器
            elem = opts.elem,
            tmp = new Date().getTime(),
            // 弹框标题
            title = opts.title || '数据选择',
            // 选择框图标
            icon = opts.icon || 'layui-icon-search',
            // 默认提示语
            placeholder = opts.placeholder || '',
            url = opts.url,
            // 是否开启搜索：true/false
            search = opts.search == null ? true : opts.search,
            //多选
            check = opts.check == null ? false : opts.check,
            //是否可编辑
            edit = opts.edit == null ? false : opts.edit,
            //类型(1、部门树，2、用户树，3、区域树)
            type = opts.type || '',
            //排除掉的编号
            extId = opts.extId || '',
            rootId = opts.rootId || '',
            isParent = opts.isParent || false,
            value = opts.value || '',
            label = opts.label || '',
            TREE_BODY = 'layui-treeSelect-' + tmp,
            PICKER_BODY = 'layui-treeSelect-body-' + tmp;
        var a = {
            init: function () {
                a.hideElem().createSelect().createBody();
                common.loadCss();
                return a;
            },
            /**
             * 隐藏elem
             */
            hideElem: function () {
                $(elem).hide();
                //赋初始值
                if (value !== undefined && value !== null && value !== '') {
                    $(elem).val(value);
                }
                return a;
            },
            /**
             * 绘制选择框
             */
            createSelect: function () {
                var selectHtml = '<div class="lg" id="' + TREE_BODY + '">' +
                    '<input type="text" readonly class="layui-input" placeholder="' + placeholder + '" value="' + label + '">' +
                    '</div>';
                $(elem).after(selectHtml);
                return a;
            },
            /**
             * 绘制主体部分
             */
            createBody: function () {
                var item = '#' + TREE_BODY;
                var params = {
                    'url': url,
                    'type': type,
                    'extId': extId,
                    'search': search,
                    'check': check,
                    'edit': edit,
                    'rootId': rootId,
                    'elem': elem,
                    'showElem': item,
                    'value': value,
                    'label': label
                };
                a.event('click', item, function () {
                    //页面层
                    // layer.open({
                    //     title: title,
                    //     type: 1,
                    //     maxmin: true,
                    //     // skin: 'layui-layer-rim', //加上边框
                    //     area: ['350px', '450px'], //宽高
                    //     content: 'html内容' ,
                    //     btn: ['确定', '清除', '取消']
                    // });

                    top.layer.open({
                        type: 2
                        , title: title
                        , content: '/tree?' + $.param(params)
                        , area: ['350px', '480px']
                        , shadeClose: false
                        , btn: ['确定', '清除', '取消']
                        , yes: function (index, layero) {
                            var iframeWindow = top['layui-layer-iframe' + index];
                            var ids = [], names = [], nodes = [];

                            if (check === true) {
                                nodes = iframeWindow.zTreeObj.getCheckedNodes(true)
                            } else {
                                nodes = iframeWindow.zTreeObj.getSelectedNodes();
                            }

                            //检查是否选中
                            if (nodes.length == 0) {
                                layer.msg(TIPS);
                                return false
                            }

                            for (var i = 0; i < nodes.length; i++) {
                                if (isParent && nodes[i].isParent) {
                                    continue; // 如果为复选框选择，则过滤掉父节点
                                }
                                ids.push(nodes[i].id);
                                names.push(nodes[i].name);
                            }
                            $(elem).val(ids);
                            $(item).children('input').val(names);
                            top.layer.close(index);
                        }, btn2: function (index, layero) {
                            var iframeWindow = top['layui-layer-iframe' + index];
                            iframeWindow.zTreeObj.cancelSelectedNode();
                            $(elem).val('');
                            $(item).children('input').val('');
                            return false// 开启该代码可禁止点击该按钮关闭
                        }
                    });
                });
                return a;
            },
            /**
             * 搜索
             */
            search: function () {
                var item = '#' + PICKER_BODY + ' .layui-treeSelect-search .layui-input';
                a.event('input propertychange', item, function (e) {
                    var elem = e.target,
                        t = $(elem).val();
                    a.createList(t);
                });
                return a;
            },
            event: function (evt, el, fn) {
                $(BODY).on(evt, el, fn);
            }
        };

        var common = {
            /**
             * 加载样式表
             */
            loadCss: function () {
                var css = '.lg {\n' +
                   /* '        float: left;\n' +*/
                    '        margin-left: 0;\n' +
                    '        overflow: hidden;\n' +
                    '        border: 1px solid #e6e6e6;\n' +
                    '        border-radius: 2px;\n' +
                    '        height: 36px\n' +
                    '    }\n' +
                    '\n' +
                    '    .lg:hover {\n' +
                    '        border: 1px solid #D2D2D2 !important;\n' +
                    '        cursor: pointer;\n' +
                    '    }\n' +
                    '\n' +
                    '    .lg input {\n' +
                    '        width: 75%;\n' +
                    '        float: left;\n' +
                    '        border: none;\n' +
                    '    }\n' +
                    '\n' +
                    '    .lg input:hover {\n' +
                    '        cursor: pointer;\n' +
                    '    }\n' +
                    '\n' +
                    '    .lg button {\n' +
                    '        float: right;\n' +
                    '        width: 20%;\n' +
                    '        border: none;\n' +
                    '        border-left: 1px solid #e6e6e6;\n' +
                    '    }\n' +
                    '\n' +
                    '    .lg i.layui-treeselect-icon {\n' +
                    '        position: relative;\n' +
                    '        line-height: normal;\n' +
                    '        right: 5px;\n' +
                    '        top: -2px;\n' +
                    '        vertical-align: middle;\n' +
                    '    }';
                $('head').append('<style rel="stylesheet">' + css + '</style>');
            }
        };

        a.init();
        return new TreeSelect();
    };

    var treeSelect = new TreeSelect();
    exports(_MOD, treeSelect);
});